package com.aspire.boc.mms.gwcmp.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.aspire.boc.mms.gwcmp.dao.GwcmpChannelMapper;
import com.aspire.boc.mms.gwcmp.model.GwcmpBilling;
import com.aspire.boc.mms.gwcmp.model.GwcmpChannel;
import com.aspire.boc.mms.gwcmp.model.GwcmpChannelExample;
import com.aspire.boc.mms.gwcmp.util.CapChecker;
import com.aspire.boc.mms.gwcmp.util.CheckResult;
import com.aspire.boc.mms.gwcmp.util.GwcmpAdminUtil;
import com.aspire.boc.mms.gwcmp.util.enums.CapParamName;
import com.aspire.boc.mms.wmf.util.Page;
import com.aspire.boc.mms.wmf.util.ResourceManager;

/**
 * 通道信息
 * @author liming
 *
 */
@Controller
public class ChannelAct {

	private static Log logger = LogFactory.getLog(ChannelAct.class);
	
	@Autowired
	private GwcmpChannelMapper channelDao;
	
	ResourceManager resourceManager = ResourceManager.getInstance();
	
	@RequestMapping(value = "/channel/saveChannel.do")
	public @ResponseBody Map<String,Object> saveChannel(
			@RequestParam(value = "id", required = false) String id,						//通道ID
			@RequestParam(value = "channelName", required = false) String channelName,		//通道名称
			@RequestParam(value = "channelType", required = false) Short channelType,		//通道类型.1:彩信;2:短信
			@RequestParam(value = "carrier", required = false) Short carrier,				//所属运营商.1:移动;2:联通;3:电信
			@RequestParam(value = "protocalType", required = false) String protocalType,	//协议类型.短信对应CMPP或HTTP;彩信:MM7
			@RequestParam(value = "billingType", required = false) Short billingType,		//计费方式.1:包月;2:包条;3:包年
			@RequestParam(value = "channelPrice", required = false) String channelPrice,	//通道价格
			@RequestParam(value = "needSharing", required = false) String needSharing,		//是否分成.0:否;1:是
			@RequestParam(value = "sharingRate", required = false) String sharingRate,		//分成比例.单位百分比.为0表示不分成
			@RequestParam(value = "flowControl", required = false) String flowControl,		//流量控制.-1:不限制;其他:具体数值/s
			@RequestParam(value = "capName", required = false) String capName,				//能力接口的名称，对应代码中的annotation中的name
			@RequestParam(value = "capClassname", required = false) String capClassname,	//cap处理模块的类名
			@RequestParam(value = "capBusiness", required = false) String capBusiness,		//cap处理模块的业务参数
			@RequestParam(value = "capStart", required = false) String capStart,			//处理模块的启动参数(使用"key1=value1,key2=value2"的properties形式表示)
			HttpServletRequest request, HttpServletResponse response){
		
		Map<String,Object> result = new HashMap<String, Object>();
		RequestContext requestContext = new RequestContext(request);
		
		//获取 操作人名称
		String operator = GwcmpAdminUtil.getLoginUserName(request);
		
		StringBuffer logInfo = new StringBuffer();
		logInfo.append("operator:").append(operator).append(",operation:/channel/saveChannel.do")
			.append(",params:[").append("id=").append(id).append(",channelName=").append(channelName)
			.append(",channelType=").append(channelType).append(",carrier=").append(carrier).append(",protocalType=").append(protocalType)
			.append(",billingType=").append(billingType).append(",channelPrice=").append(channelPrice).append(",needSharing=").append(needSharing)
			.append(",sharingRate=").append(sharingRate).append(",flowControl=").append(flowControl).append(",capName=").append(capName)
			.append(",capClassname=").append(capClassname).append(",capBusiness=").append(capBusiness).append(",capStart=").append(capStart).append("] ");
		logger.info(logInfo.toString());
		
		GwcmpChannel channel = new GwcmpChannel();
		channel.setLatestOperator(operator);
		channel.setLatestOperateTime(new Date());
		//通道名称不为空
		if(channelName==null||channelName.length()==0){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[channelName] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.channelNameNull"));
			return result;
		}
		if(channelName.length()>127){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[channelName] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.channelNameTooLang"));
			return result;
		}
		channel.setChannelName(channelName);
		//计费方式不为空
		if(billingType==null){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[billingType] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.billingTypeNull"));
			return result;
		}
		channel.setBillingType(billingType);
		//通道类型不为空
		if(channelType==null){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[channelType] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.channelTypeNull"));
			return result;
		}
		channel.setChannelType(channelType);
		//所属运营商不为空
		if(carrier==null){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[carrier] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.carrierNull"));
			return result;
		}
		channel.setCarrier(carrier);
		//协议类型不为空
		if(StringUtils.isBlank(protocalType)){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[carrier] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.protocalTypeNull"));
			return result;
		}
		channel.setProtocalType(protocalType.trim());
		//通道价格
		String regex = "[0-9]{1,10}(\\.[0-9]{1,2})?";
		if(channelPrice!=null&&!regexCheck(regex,channelPrice)){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[channelPrice]:"+channelPrice);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.channelPrice"));
			return result;
		}
		channel.setChannelPrice(channelPrice==null?null:new BigDecimal(channelPrice));
		//分成比例：0-99.99，可空
		sharingRate = StringUtils.trimToNull(sharingRate);
		regex = "[0-9]{1,2}(\\.[0-9]{1,2})?";
		if(sharingRate!=null&&!regexCheck(regex,sharingRate)){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[sharingRate]:"+sharingRate);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.sharingRate"));
			return result;
		}
		channel.setSharingRate(sharingRate==null?new BigDecimal(0):new BigDecimal(sharingRate));
		//是否分成 非1即0
		Short needSharingShort = 0;
		if("1".equals(needSharing)){
			needSharingShort=1;
		}
		channel.setNeedSharing(needSharingShort);
		
		flowControl = StringUtils.trimToNull(flowControl);
		regex = "-1|[0-9]{1,10}?";
		if(flowControl!=null&&!regexCheck(regex,flowControl)){
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:[flowControl]:"+flowControl);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.flowControl"));
			return result;
		}
		
		//流量控制.-1:不限制;其他:具体数值/s
		channel.setFlowControl(flowControl==null?new Long(-1):new Long(flowControl));
		//cap处理模块的类名
		channel.setCapClassname(capClassname);
		//cap处理模块的业务参数 去空格
		capBusiness = capBusiness==null?null:capBusiness.replace(" ", "");
		CheckResult checkResult = CapChecker.checkParams(requestContext, capClassname, CapParamName.CAP_BUSINESS, capBusiness);
		if(!checkResult.isOk()){
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",checkResult.getErrorMsgString("<br>"));
			return result;
		}
		channel.setCapBusiness(capBusiness);
		//处理模块的启动参数(使用"key1=value1,key2=value2"的properties形式表示) 去空格
		capStart = capStart==null?null:capStart.replace(" ", "");
		checkResult = CapChecker.checkParams(requestContext, capClassname, CapParamName.CAP_START, capStart);
		if(!checkResult.isOk()){
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",checkResult.getErrorMsgString("<br>"));
			return result;
		}
		channel.setCapStart(capStart);
		//能力接口的名称
		channel.setCapName(capName);
		
		try {
			if(StringUtils.isNotBlank(id)){
				//更新
				channel.setId(id);
				
				int count = channelDao.updateByPrimaryKeySelective(channel);
				if(count == 0){
					result.put("failure", Boolean.valueOf(true));
					result.put("msg",requestContext.getMessage("channel.error.channelNotExist"));
					return result;
				}
			}else{
				//新增
				channel.setId(String.valueOf(channelDao.getChannelIdSequence()));
				logger.info("operator:"+operator+",operation:/channel/saveChannel.do,insertSelective("+channel+")");
				channelDao.insertSelective(channel);
			}
			result.put("success", Boolean.valueOf(true));
		} catch (Exception e) {
			logger.error("operator:"+operator+",operation:/channel/saveChannel.do,errorMsg:",e);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("common.error.systemError"));
			return result;
		}
		return result;
		
	}
	
	@RequestMapping(value = "/channel/getChannelDetail.do")
	public @ResponseBody Map<String,Object> getChannelDetail(
			@RequestParam(value = "channelId", required = false) String channelId,
			HttpServletRequest request, HttpServletResponse response){
		
		Map<String,Object> result = new HashMap<String, Object>();
		RequestContext requestContext = new RequestContext(request);
		
		//获取 操作人名称
		String operator = GwcmpAdminUtil.getLoginUserName(request);
		
		StringBuffer logInfo = new StringBuffer();
		logInfo.append("operator:").append(operator).append(",operation:/channel/editChannel.do")
			.append(",params:[").append("channelId=").append(channelId).append("] ");
		logger.info(logInfo.toString());
		
		if(StringUtils.isBlank(channelId)){
			logger.error("operator:"+operator+",operation:/channel/getChannelDetail.do,errorMsg:[channelId] is empty");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("channel.error.channelIdNull"));
			return result;
		}
		GwcmpChannel channel = null;
		try{
			channel = channelDao.selectByPrimaryKey(channelId);
		} catch (Exception e) {
			logger.error("operator:"+operator+",operation:/channel/getChannelDetail.do,errorMsg:",e);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("common.error.systemError"));
			return result;
		}
		result.put("single", channel!=null?channel:new GwcmpChannel());
		return result;
		
	}
	
	@RequestMapping(value = "/channel/getChannelList.do")
	public @ResponseBody Map<String,Object> getChannelList(
			@RequestParam(value = "start", required = true) int start,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "channelName", required = false) String channelName,
			@RequestParam(value = "channelType", required = false) Short channelType,
			HttpServletRequest request, HttpServletResponse response){
		
		Map<String,Object> result = new HashMap<String, Object>();
		RequestContext requestContext = new RequestContext(request);
		
		//获取 操作人名称
		String operator = GwcmpAdminUtil.getLoginUserName(request);
		
		StringBuffer logInfo = new StringBuffer();
		logInfo.append("operator:").append(operator).append(",operation: /channel/getChannelList.do")
			.append(",params:[").append("start=").append(start).append(",limit=").append(limit)
			.append(",channelName=").append(channelName).append(",channelType=").append(channelType).append("]");
		logger.info(logInfo.toString());
		
		channelName = StringUtils.trimToNull(channelName);
		
		// 分页
		GwcmpChannelExample channelExample = new GwcmpChannelExample();
		channelExample.setOrderByClause("LATEST_OPERATE_TIME DESC");
		Page page = new Page(start, limit);
		channelExample.setPage(page);
		GwcmpChannelExample.Criteria criteria = channelExample.createCriteria();
		if(channelName != null){
			criteria.andChannelNameLike("%"+channelName+"%");
		}
		if(channelType != null){
			criteria.andChannelTypeEqualTo(channelType);
		}
		
		List<GwcmpChannel> list = null;
		Integer total = 0;
		try{
			list = channelDao.selectByExample(channelExample);
			total = channelDao.countByExample(channelExample);
		} catch (Exception e) {
			logger.error("operator:"+operator+",operation:/channel/getChannelList.do,errorMsg:",e);
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("common.error.systemError"));
			return result;
		}	
		result.put("total", total);
		result.put("list", list==null?new ArrayList<GwcmpBilling>(0):list);
	    return result;
	}
	
	/**
	 * 正则校验 
	 * @param regex 正则规则
	 * @param msg	校验内容
	 * @return
	 */
	private boolean regexCheck(String regex,String msg){
		if(msg==null||regex==null){
			return false;
		}
		Pattern pattern = Pattern.compile(regex);  
		Matcher matcher = pattern.matcher(msg); 
		return matcher.matches();
	}
	
}
